import { useRef, useState, useEffect } from 'react';
import { useModel } from 'umi';
import ScrollText from 'react-scroll-text';
import useRequest from '@/utils/useRequestWrapper';
import { useRecursiveTimeout } from '@/utils/hooks';
import { getClassNewsList } from '@/services/ant-design-pro/api';

// 1分钟刷新一次
const DELAY_TIME = 60000;

export default () => {
  const { token } = useModel('global');
  const classNews = useRequest(getClassNewsList, { manual: true });
  const fetchClassNewsRef = useRef(classNews.run);
  fetchClassNewsRef.current = classNews.run;
  const [newsText, setNewsText] = useState();

  const fetchTableData = () => {
    fetchClassNewsRef.current(token.xxNo, token.bjNo);
  };
  const [, setIsTimerRunning] = useRecursiveTimeout(false, fetchTableData, DELAY_TIME);

  useEffect(() => {
    if (token?.bjNo) {
      setIsTimerRunning(true);
    } else {
      setIsTimerRunning(false);
    }
  }, [token, fetchClassNewsRef]);

  useEffect(() => {
    if (classNews.data) {
      if (Array.isArray(classNews.data.result) && classNews.data.result.length > 0) {
        const fetchedText = classNews.data.result[0].content;
        if (fetchedText !== newsText) {
          setNewsText(fetchedText);
        }
      } else {
        setNewsText();
      }
    }
  }, [classNews.data]);

  return (
    <ScrollText style={{ color: '#FF8F1E', fontSize: 32, width: 900, marginLeft: 20 }}>
      {newsText || ''}
    </ScrollText>
  );
};
